<template>
  <div class="create-index-container">
    <div class="form-container">
      <!-- 索引名输入 -->
      <div class="form-group">
        <label for="indexName">索引名：</label>
        <input 
          id="indexName"
          v-model="indexForm.name"
          @input="validateIndexName"
          placeholder="请输入索引名（小写，不含特殊字符）"
          class="form-control"
          :class="{ 'is-invalid': indexNameError }"
        />
        <div v-if="indexNameError" class="invalid-feedback">
          {{ indexNameError }}
        </div>
      </div>

      <!-- 字段配置区 -->
      <div class="section">
        <div class="section-header">
          <h3>字段配置</h3>
          <button @click="addField" class="btn btn-secondary btn-sm">新增字段</button>
        </div>
        
        <div class="fields-table">
          <div class="table-header">
            <div class="field-col">字段名</div>
            <div class="type-col">SQL类型</div>
            <div class="es-config-col">ES扩展配置</div>
            <div class="action-col">操作</div>
          </div>
          
          <div 
            v-for="(field, index) in indexForm.fields" 
            :key="index" 
            class="table-row"
          >
            <!-- 字段名 -->
            <div class="field-col">
              <input 
                v-model="field.name"
                placeholder="字段名"
                class="form-control form-control-sm"
              />
            </div>
            
            <!-- SQL类型 -->
            <div class="type-col">
              <select v-model="field.sqlType" class="form-control form-control-sm">
                <option value="">请选择</option>
                <option value="INT">INT</option>
                <option value="BIGINT">BIGINT</option>
                <option value="VARCHAR">VARCHAR</option>
                <option value="TEXT">TEXT</option>
                <option value="DATE">DATE</option>
                <option value="DECIMAL">DECIMAL</option>
                <option value="BOOLEAN">BOOLEAN</option>
              </select>
            </div>
            
            <!-- ES扩展配置 -->
            <div class="es-config-col">
              <div v-if="field.sqlType === 'INT'" class="es-config-item">
                <select v-model="field.esType" class="form-control form-control-sm">
                  <option value="integer">integer</option>
                  <option value="long">long</option>
                </select>
              </div>
              
              <div v-else-if="field.sqlType === 'VARCHAR' || field.sqlType === 'TEXT'" class="es-config-item">
                <select v-model="field.esType" class="form-control form-control-sm">
                  <option value="text">text</option>
                  <option value="keyword">keyword</option>
                </select>
                <select 
                  v-if="field.esType === 'text'" 
                  v-model="field.analyzer" 
                  class="form-control form-control-sm"
                >
                  <option value="">默认分词器</option>
                  <option value="standard">standard</option>
                  <option value="ik_max_word">ik_max_word</option>
                  <option value="ik_smart">ik_smart</option>
                </select>
              </div>
              
              <div v-else-if="field.sqlType === 'DATE'" class="es-config-item">
                <input 
                  v-model="field.format" 
                  placeholder="格式如：yyyy-MM-dd" 
                  class="form-control form-control-sm"
                />
              </div>
              
              <div v-else-if="field.sqlType === 'DECIMAL'" class="es-config-item">
                <input 
                  v-model="field.scalingFactor" 
                  type="number" 
                  placeholder="scaling_factor 如：100" 
                  class="form-control form-control-sm"
                />
              </div>
              
              <div v-else class="es-config-item">
                <span class="text-muted">无额外配置</span>
              </div>
            </div>
            
            <!-- 操作 -->
            <div class="action-col">
              <button @click="removeField(index)" class="btn btn-danger btn-sm">删除</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 索引设置区 -->
      <div class="section">
        <h3>索引设置</h3>
        <div class="settings-grid">
          <div class="form-group">
            <label for="numberOfShards">分片数：</label>
            <input 
              id="numberOfShards"
              v-model.number="indexForm.settings.numberOfShards"
              type="number"
              min="1"
              class="form-control"
            />
          </div>
          
          <div class="form-group">
            <label for="numberOfReplicas">副本数：</label>
            <input 
              id="numberOfReplicas"
              v-model.number="indexForm.settings.numberOfReplicas"
              type="number"
              min="0"
              class="form-control"
            />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <button @click="generateSQL" class="btn btn-secondary">生成SQL</button>
        <button 
          @click="createIndex" 
          class="btn btn-primary"
          :disabled="creatingIndex"
        >
          <span v-if="creatingIndex">创建中...</span>
          <span v-else>创建索引</span>
        </button>
        <button @click="close" class="btn btn-default">关闭</button>
      </div>

      <!-- 结果展示区 -->
      <div v-if="resultMessage" class="result-message" :class="resultType">
        {{ resultMessage }}
      </div>

      <!-- SQL预览区 -->
      <div v-if="generatedSQL" class="sql-preview">
        <h4>生成的CREATE TABLE语句：</h4>
        <pre><code>{{ generatedSQL }}</code></pre>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { API_BASE_URL } from '../api/config.js';

export default {
  name: 'CreateIndex',
  props: {
    isConnected: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      showForm: false,
      creatingIndex: false,
      indexNameError: '',
      resultMessage: '',
      resultType: 'success',
      generatedSQL: '',
      indexForm: {
        name: '',
        fields: [],
        settings: {
          numberOfShards: 1,
          numberOfReplicas: 0
        }
      }
    };
  },
  methods: {
    toggleForm() {
      this.showForm = !this.showForm;
    },
    
    validateIndexName() {
      const name = this.indexForm.name;
      if (!name) {
        this.indexNameError = '';
        return;
      }
      
      // 检查是否为小写字母、数字和下划线组成
      if (!/^[a-z0-9_]+$/.test(name)) {
        this.indexNameError = '索引名只能包含小写字母、数字和下划线';
        return;
      }
      
      // 检查长度
      if (name.length > 255) {
        this.indexNameError = '索引名不能超过255个字符';
        return;
      }
      
      this.indexNameError = '';
    },
    
    addField() {
      this.indexForm.fields.push({
        name: '',
        sqlType: '',
        esType: '',
        analyzer: '',
        format: '',
        scalingFactor: ''
      });
    },
    
    removeField(index) {
      this.indexForm.fields.splice(index, 1);
    },
    
    generateSQL() {
      if (!this.indexForm.name) {
        this.showResult('请先输入索引名', 'error');
        return;
      }
      
      if (this.indexForm.fields.length === 0) {
        this.showResult('请至少添加一个字段', 'error');
        return;
      }
      
      let sql = `CREATE TABLE \`${this.indexForm.name}\` (\n`;
      
      const fields = this.indexForm.fields.map(field => {
        let fieldDef = `  \`${field.name}\` ${field.sqlType}`;
        
        // 添加ES特定配置作为注释
        if (field.sqlType === 'INT' && field.esType) {
          fieldDef += ` /* ES类型: ${field.esType} */`;
        } else if ((field.sqlType === 'VARCHAR' || field.sqlType === 'TEXT') && field.esType) {
          fieldDef += ` /* ES类型: ${field.esType}`;
          if (field.analyzer) {
            fieldDef += `, 分词器: ${field.analyzer}`;
          }
          fieldDef += ' */';
        } else if (field.sqlType === 'DATE' && field.format) {
          fieldDef += ` /* 格式: ${field.format} */`;
        } else if (field.sqlType === 'DECIMAL' && field.scalingFactor) {
          fieldDef += ` /* scaling_factor: ${field.scalingFactor} */`;
        }
        
        return fieldDef;
      });
      
      sql += fields.join(',\n');
      sql += '\n)';
      
      // 添加设置
      sql += ` SETTINGS "index.number_of_shards" = ${this.indexForm.settings.numberOfShards}, `;
      sql += `"index.number_of_replicas" = ${this.indexForm.settings.numberOfReplicas};`;
      
      this.generatedSQL = sql;
      this.showResult('SQL生成成功', 'success');
    },
    
    async createIndex() {
      // 验证表单
      if (!this.isConnected) {
        this.showResult('请先连接到Elasticsearch', 'error');
        return;
      }
      
      if (!this.indexForm.name) {
        this.showResult('请输入索引名', 'error');
        return;
      }
      
      if (this.indexNameError) {
        this.showResult('索引名格式不正确', 'error');
        return;
      }
      
      if (this.indexForm.fields.length === 0) {
        this.showResult('请至少添加一个字段', 'error');
        return;
      }
      
      // 验证字段
      for (const field of this.indexForm.fields) {
        if (!field.name) {
          this.showResult('字段名不能为空', 'error');
          return;
        }
        
        if (!field.sqlType) {
          this.showResult('请选择字段的SQL类型', 'error');
          return;
        }
      }
      
      this.creatingIndex = true;
      this.resultMessage = '';
      
      try {
        // 构建映射
        const mapping = this.buildMapping();
        
        // 发送请求
        const response = await axios.post(`${API_BASE_URL}/api/es/indices`, {
          indexName: this.indexForm.name,
          mapping: JSON.stringify(mapping)
        });
        
        if (response.data.success) {
          this.showResult(`索引 "${this.indexForm.name}" 创建成功`, 'success');
          // 重置表单
          this.resetForm();
          // 通知父组件刷新索引列表
          this.$emit('index-created');
        } else {
          this.showResult(response.data.message || '索引创建失败', 'error');
        }
      } catch (error) {
        console.error('创建索引失败:', error);
        this.showResult('创建索引失败: ' + (error.response?.data?.message || error.message), 'error');
      } finally {
        this.creatingIndex = false;
      }
    },
    
    buildMapping() {
      const mapping = {
        settings: {
          number_of_shards: this.indexForm.settings.numberOfShards,
          number_of_replicas: this.indexForm.settings.numberOfReplicas
        },
        mappings: {
          properties: {}
        }
      };
      
      for (const field of this.indexForm.fields) {
        const property = {};
        
        switch (field.sqlType) {
          case 'INT':
            property.type = field.esType || 'integer';
            break;
          case 'BIGINT':
            property.type = 'long';
            break;
          case 'VARCHAR':
          case 'TEXT':
            property.type = field.esType || 'text';
            if (property.type === 'text' && field.analyzer) {
              property.analyzer = field.analyzer;
            }
            break;
          case 'DATE':
            property.type = 'date';
            if (field.format) {
              property.format = field.format;
            }
            break;
          case 'DECIMAL':
            property.type = 'scaled_float';
            if (field.scalingFactor) {
              property.scaling_factor = parseInt(field.scalingFactor);
            }
            break;
          case 'BOOLEAN':
            property.type = 'boolean';
            break;
          default:
            property.type = 'text';
        }
        
        mapping.mappings.properties[field.name] = property;
      }
      
      return mapping;
    },
    
    showResult(message, type) {
      this.resultMessage = message;
      this.resultType = type;
    },
    
    resetForm() {
      this.indexForm = {
        name: '',
        fields: [],
        settings: {
          numberOfShards: 1,
          numberOfReplicas: 0
        }
      };
      this.generatedSQL = '';
    },
    
    close() {
      this.$emit('close-modal');
    }
  }
};
</script>

<style scoped>
.create-index-container {
  width: 100%;
}

.form-container {
  padding: 16px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  color: #2D3748;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #E2E8F0;
  border-radius: 4px;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  transition: border-color 0.15s;
  box-sizing: border-box;
}

.form-control:focus {
  border-color: #4299E1;
  outline: 0;
}

.form-control-sm {
  padding: 6px 8px;
  font-size: 13px;
}

.is-invalid {
  border-color: #E53E3E;
}

.invalid-feedback {
  display: block;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 0.875em;
  color: #E53E3E;
}

.section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.section h3 {
  font-size: 15px;
  color: #2D3748;
  margin: 0;
}

.fields-table {
  border: 1px solid #E2E8F0;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: flex;
  background-color: #F7FAFC;
  font-weight: 500;
  padding: 10px;
  border-bottom: 1px solid #E2E8F0;
}

.table-row {
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #E2E8F0;
}

.table-row:last-child {
  border-bottom: none;
}

.field-col {
  flex: 2;
  padding: 0 5px;
}

.type-col {
  flex: 2;
  padding: 0 5px;
}

.es-config-col {
  flex: 3;
  padding: 0 5px;
}

.action-col {
  flex: 1;
  padding: 0 5px;
  display: flex;
  align-items: center;
}

.es-config-item {
  display: flex;
  gap: 5px;
}

.settings-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: flex-end;
}

.btn {
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  font-family: 'Inter', sans-serif;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #4299E1;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #3182CE;
}

.btn-secondary {
  background-color: #718096;
  color: white;
}

.btn-secondary:hover {
  background-color: #4A5568;
}

.btn-default {
  background-color: #EDF2F7;
  color: #4A5568;
}

.btn-default:hover {
  background-color: #E2E8F0;
}

.btn-sm {
  padding: 5px 10px;
  font-size: 13px;
}

.btn-danger {
  background-color: #E53E3E;
  color: white;
}

.btn-danger:hover {
  background-color: #C53030;
}

.result-message {
  margin-top: 15px;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
}

.result-message.success {
  background-color: #F0FFF4;
  color: #38A169;
  border: 1px solid #9AE6B4;
}

.result-message.error {
  background-color: #FFF5F5;
  color: #E53E3E;
  border: 1px solid #FEB2B2;
}

.sql-preview {
  margin-top: 20px;
}

.sql-preview h4 {
  font-size: 14px;
  margin-bottom: 8px;
}

.sql-preview pre {
  background-color: #F7FAFC;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 13px;
  margin: 0;
}

.text-muted {
  color: #A0AEC0;
  font-size: 13px;
}
</style>